﻿@page "/download"
@using System.Runtime.InteropServices
@attribute [StreamRendering]
@inject HttpClient client
@inject IConfiguration config

<PageTitle>下载</PageTitle>

<div style="padding:20px;">
    <h1>常用工具</h1>

    <p>提供常用的工具：日志分析工具、IPv6获取工具、下位机模拟器等。</p>

    <hr />
    @if (apps == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table" style="width:100%">
            <thead>
                <tr>
                    <th>AppName</th>
                    <th>Version</th>
                    <th>UpdateTime</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var forecast in apps)
                {
                    <tr>
                        <td><a href=@forecast.DownloadPath>@forecast.AppName</a></td>
                        <td>@forecast.Version</td>
                        <td>@forecast.UpdateTime</td>
                        <td>@forecast.Description</td>
                    </tr>
                }
            </tbody>
        </table>
        <p>@errorMessage</p>
    }
</div>

@code {
    private DownloadApp[]? apps;
    private string? errorMessage;
    private string? address;
    protected override async Task OnInitializedAsync()
    {
        try
        {
            List<DownloadApp>? appList = new List<DownloadApp>();
            if (client.BaseAddress == null)
            {
                var response = await client.GetAsync($"{config.GetValue<string>("Kestrel:Endpoints:Http:Url")}/api/tools");
                response.EnsureSuccessStatusCode();
                appList = await response.Content.ReadFromJsonAsync<List<DownloadApp>>();
            }
            if (appList != null && appList.Count > 0)
            {
                apps = appList.ToArray();
            }
            else
            {
                errorMessage = "服务器上没有找到应用";
                apps = Array.Empty<DownloadApp>();
            }
        }
        catch (Exception ex)
        {
            errorMessage = $"加载应用列表时发生错误: {ex.Message}";
            apps = Array.Empty<DownloadApp>();
        }
    }

    public class DownloadApp
    {
        public string AppName { get; set; } = string.Empty;
        public string Titile { get; set; } = string.Empty;
        public DateTime UpdateTime { get; set; }
        public string Version { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string DownloadPath { get; set; } = string.Empty;
    }
}
